package com.km.team.phsystem.service.impl;

import com.km.team.phsystem.beans.pojo.TemporaryAppointment;
import com.km.team.phsystem.beans.pojo.TimeSlotPhConfig;
import com.km.team.phsystem.beans.pojo.TimeSlotPhConfigExample;
import com.km.team.phsystem.beans.vo.TimeSlot;
import com.km.team.phsystem.beans.vo.TimeSlotVo;
import com.km.team.phsystem.dao.mybatis.TimeSlotPhConfigMapper;
import com.km.team.phsystem.dao.mybatis.custom.TimeSlotPhConfigMapperCustom;
import com.km.team.phsystem.service.TemporaryAppointmentService;
import com.km.team.phsystem.service.TimeSlotPhConfigService;
import com.km.team.phsystem.service.impl.base.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：Riven.
 * @description： 业务办理时间段服务层
 * @date ：2018/11/30
 */
@Service("timeSlotPhConfigService")
public class TimeSlotPhConfigServiceImpl
    extends BaseService<TimeSlotPhConfigServiceImpl, TimeSlotPhConfig> implements TimeSlotPhConfigService {
    private final TimeSlotPhConfigMapper timeSlotPhConfigMapper;
    private final TimeSlotPhConfigMapperCustom timeSlotPhConfigMapperCustom;
    private final TemporaryAppointmentService temporaryAppointmentService;

    @Autowired
    public TimeSlotPhConfigServiceImpl(
        TimeSlotPhConfigMapper timeSlotPhConfigMapper,
        TimeSlotPhConfigMapperCustom timeSlotPhConfigMapperCustom,
        TemporaryAppointmentService temporaryAppointmentService) {
        this.timeSlotPhConfigMapper = timeSlotPhConfigMapper;
        this.timeSlotPhConfigMapperCustom = timeSlotPhConfigMapperCustom;
        this.temporaryAppointmentService = temporaryAppointmentService;
    }

    @Override
    public List<TimeSlotPhConfig> getTimeSlotInfoForBusiness(Integer businessId) {
        return this.timeSlotPhConfigMapper.selectByExample(getTimeSlotPhConfigExample(businessId));
    }

    private TimeSlotPhConfigExample getTimeSlotPhConfigExample(Integer businessId) {
        TimeSlotPhConfigExample timeSlotPhConfigExample = new TimeSlotPhConfigExample();
        timeSlotPhConfigExample.or().andSystemBusitypeIdEqualTo(businessId);
        return timeSlotPhConfigExample;
    }

    @Override
    public void instOrUpdateTimeSlot(List<TimeSlotPhConfig> newDataList, Integer businessId, Integer taaNo) {
        //处理临时业务
        temporaryBusinessHandle(businessId, taaNo);
        //处理预约业务
        List<TimeSlotPhConfig> newList = new ArrayList<>(16);
        List<TimeSlotPhConfig> resetList = new ArrayList<>(16);
        newDataList.forEach(item -> {
            if (item.getId() == null) {
                newList.add(item);
            } else {
                resetList.add(item);
            }
        });
        resetList.forEach(item -> {
            if (!item.getIsEnable()) {
                item.setSystemBusitypeId(businessId);
                item.setAcceptNo(0);
                item.setIsEnable(false);
            }
        });
        if (newList.size() != 0) {
            int i = this.timeSlotPhConfigMapperCustom.batchInst(newList);
            logger.info("批量插入成功，插入数量： " + i);
        }
        if (resetList.size() != 0) {
            int update = this.timeSlotPhConfigMapperCustom.batchUpdate(resetList);
            logger.info("批量跟新成功，插入数量： " + update);
        }
    }

    /**
     * 处理临时业务逻辑
     *
     * @param businessId 业务ID
     * @param taaNo      临时受理数量
     */
    private void temporaryBusinessHandle(Integer businessId, Integer taaNo) {
        List<TemporaryAppointment> temporaryAppointments =
            this.temporaryAppointmentService.selectForBusinessId(businessId);
        if (CollectionUtils.isEmpty(temporaryAppointments)) {
            //需要初始化
            this.temporaryAppointmentService.insert(businessId, taaNo);
        } else {
            //跟新
            this.temporaryAppointmentService.update(temporaryAppointments, taaNo);
        }
    }


    /**
     * 根据业务ID删除所有该数据的日期信息
     *
     * @param businessId 业务ID
     */
    @Override
    public void deleteForBusiness(Integer businessId) {
        List<TimeSlotPhConfig> timeSlotPhConfigs =
            this.timeSlotPhConfigMapper.selectByExample(getTimeSlotPhConfigExample(businessId));
        this.timeSlotPhConfigMapperCustom.batchDelete(timeSlotPhConfigs);
        this.timeSlotPhConfigMapper.deleteByExample(getTimeSlotPhConfigExample(businessId));
    }

    /**
     * 根据ID获取数据
     *
     * @param key
     */
    @Override
    public TimeSlotPhConfig getDataForKey(Integer key) {
        return this.timeSlotPhConfigMapper.selectByPrimaryKey(key);
    }

    @Override
    public List<TimeSlotPhConfig> selectForIdList(List<Integer> idList) {
        TimeSlotPhConfigExample timeSlotPhConfigExample = new TimeSlotPhConfigExample();
        timeSlotPhConfigExample.or().andIdIn(idList);
        return this.timeSlotPhConfigMapper.selectByExample(timeSlotPhConfigExample);
    }

    @Override
    public Integer getAcceptancesNumForBusinessId(Integer businessId) {
        Integer result = 0;
        for (TimeSlotPhConfig config : getTimeSlotPhConfigListForEnable(businessId)) {
            result += config.getAcceptNo();
        }
        return result;

    }


    private List<TimeSlotPhConfig> getTimeSlotPhConfigListForEnable(Integer businessId) {
        TimeSlotPhConfigExample timeSlotPhConfigExample = new TimeSlotPhConfigExample();
        timeSlotPhConfigExample.or().andSystemBusitypeIdEqualTo(businessId)
            .andIsEnableEqualTo(true);
        return this.timeSlotPhConfigMapper.selectByExample(timeSlotPhConfigExample);
    }

    @Override
    public TimeSlotVo getEnableTimeSlotListForBusinessId(Integer businessId, Date date) {
        List<TimeSlotPhConfig> enable = this.getTimeSlotPhConfigListForEnable(businessId);
        TimeSlotVo timeSlotVo = new TimeSlotVo();
        List<TimeSlot> timeSlotList = timeSlotVo.getTimeSlotList();
        enable.forEach(item -> {
            if (!DateUtils.isSameDay(date, new Date())) {
                //不是今天
                TimeSlot timeSlot = getTimeSlot(item, false);
                timeSlotList.add(timeSlot);
            } else {
                //是今天，需要判断是否已超过排号时间
                LocalTime startTime = LocalTime.parse(item.getEndTime());
                LocalTime nowTime = LocalTime.now().withSecond(0).withNano(0);

                if (startTime.isBefore(nowTime)) {
                    //已经超过排号时间，同样显示，但是不允许排号
                    TimeSlot timeSlot = getTimeSlot(item, true);
                    timeSlotList.add(timeSlot);
                } else {
                    //还在排号时段内
                    TimeSlot timeSlot = getTimeSlot(item, false);
                    timeSlotList.add(timeSlot);
                }

            }
        });
        timeSlotVo.setTimeSlotList(timeSlotList);
        return timeSlotVo;

    }

    private TimeSlot getTimeSlot(TimeSlotPhConfig item, Boolean enableTimeSlot) {
        TimeSlot timeSlot = new TimeSlot();
        timeSlot.setTimeSlotId(item.getId());
        timeSlot.setStartTime(item.getStartTime());
        timeSlot.setEndTime(item.getEndTime());
        timeSlot.setAcceptNo(Long.valueOf(item.getAcceptNo()));
        timeSlot.setAvailable(false);
        timeSlot.setEnableTimeSlot(enableTimeSlot);
        return timeSlot;
    }

    @Override
    public Integer getAcceptancesNumForBusinessIdAndTimeSlotId(String timeSlotId) {
        TimeSlotPhConfig timeSlotPhConfig = this.timeSlotPhConfigMapper.selectByPrimaryKey(Integer.valueOf(timeSlotId));
        return timeSlotPhConfig.getAcceptNo();
    }


}
